package com.slowfly.rule.engine.listener;

import com.slowfly.rule.engine.bean.CacheBean;
import com.slowfly.rule.engine.constants.IRiskConstants;
import com.slowfly.rule.engine.service.IDecisionService;
import com.slowfly.rule.engine.service.IRuleService;
import com.slowfly.rule.engine.service.ISceneService;
import com.slowfly.rule.engine.service.IStrategyService;
import com.slowfly.rule.engine.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RedisMessageListener implements MessageListener {

    @Autowired
    private ISceneService sceneService;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IRuleService ruleService;
    @Autowired
    private IDecisionService decisionService;

    /**
     * 订阅消息
     */
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel());
        String payload = new String(message.getBody());
        log.info("onMessage {} {}", channel, payload);
        try {
            CacheBean bean = JsonUtils.fromJson(payload, CacheBean.class);
            switch (channel) {
                case IRiskConstants.SCENE_CHANEL:
                    sceneService.editCache(bean.getType(), bean.getId());
                    break;
                case IRiskConstants.STRATEGY_CHANEL:
                    strategyService.editCache(bean.getType(), bean.getId());
                    break;
                case IRiskConstants.RULE_CHANEL:
                    ruleService.editCache(bean.getType(), bean.getId());
                    break;
                case IRiskConstants.DECISION_CHANEL:
                    decisionService.editCache(bean.getType(), bean.getId());
                    break;
            }
        } catch (Exception e) {
            log.error("onMessage error {} {}", channel, payload);
        }
    }
}